#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import cgi
import json
import db_conf
import time
#import random
con = None

def post_new_project(cur, project_name):
    try:
        cur.execute("insert into project (project_name) values ('" + project_name + "') RETURNING project_id")
        return cur.fetchone()[0]	
    except psycopg2.DatabaseError, e:
        print 'Adding new project error %s' % e
 
def post_experiment(cur, title, experimenter, exp_date, exp_project, keywords, description, ops, eid=0):
    try:
        if (ops == 'insert_experiment'):
    	    cur.execute("""insert into experiment (project_id, title, short_description, description, date, experimenter) values (%s, %s, %s, %s, to_date(%s, 'DD/MM/YYYY'), %s) RETURNING experiment_id""", (exp_project, title, keywords, description, exp_date, experimenter))
        if (ops == 'update_experiment'):
            cur.execute("""update experiment set project_id=%s, title=%s, short_description=%s,description=%s, date=%s, experimenter=%s where experiment_id = %s RETURNING experiment_id""", (exp_project, title, keywords, description, exp_date, experimenter, eid))
        return cur.fetchone()[0] 
    except psycopg2.DatabaseError, e:
        print 'Adding new experiment error %s' % e

def post_new_groups(cur, grp_name, desc, regex, sample_type_id, strain_id, type_id, experiment_id):
    
    try:
        #insert into sample_group (sample_group_id, name, description, bio_sample_type_id, strain_id, experiment_id) values (1, 'isogrp_name1', 'desc1', 2, 1, 1);
        cur.execute("""insert into sample_group (name, description, regex, bio_sample_type_id, strain_id, sample_type_id, experiment_id) values (%s, %s, %s, %s, %s, %s, %s) RETURNING sample_group_id""", (grp_name, desc, regex, sample_type_id, strain_id, type_id, experiment_id)) 
        return cur.fetchone()[0]
    except psycopg2.DatabaseError, e:
        print 'Adding new sample group error %s' % e 

def post_update_groups(cur, grp_name, desc, regex, sample_type_id, strain_id, type_id, experiment_id, sample_group_id):

    try:
        #update sample_group set (name, description, regex) = ('exp1', 'ex1 des', 'tag') where sample_group_id = 29;
        cur.execute("""update sample_group set (name, description, regex, bio_sample_type_id, strain_id, sample_type_id, experiment_id) = (%s, %s, %s, %s, %s, %s, %s) where sample_group_id = %s  RETURNING sample_group_id""", (grp_name, desc, regex, sample_type_id, strain_id, type_id, experiment_id, sample_group_id))
        return cur.fetchone()[0]
    except psycopg2.DatabaseError, e:
        print 'Adding new sample group error %s' % e


def post_chrom_groups(cur, cid, sgid, eid):
    #insert into chromatogram_sample_group (chromatogram_id, sample_group_id, experiment_id) values (1001, 1, 3);
    try:
        cur.execute("""insert into chromatogram_sample_group (chromatogram_id, sample_group_id, experiment_id) values (%s, %s, %s)""", (cid, sgid, eid))
        return 1
    except psycopg2.DatabaseError, e:
        print 'Adding new sample group error %s' % e
        return -1

try:
    qform = cgi.FieldStorage()
    project_name = qform.getvalue('project_name')
    title = qform.getvalue('exp_title')
    experimenter = qform.getvalue('exp_people')    
    exp_date = qform.getvalue('exp_date')
    if (exp_date != None and (exp_date.find("/") != -1)):
        exp_date = exp_date.split("/")[2] + "-" + exp_date.split("/")[1] + "-" + exp_date.split("/")[0]
	
    keywords = qform.getvalue('exp_keywords')
    description = qform.getvalue('exp_description')
    exp_ops = qform.getvalue("exp_ops")
    active_experiment = qform.getvalue("active_experiment")
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    cur = con.cursor()
    exp_id = ""
    pa = {}
    exp_grps = []
    if (project_name != None and project_name != "" and title == None):        
        proj_id = post_new_project(cur, project_name) 
        pa['_new_proj_id'] = proj_id
    if (title != None and title != "" and exp_ops == "insert_experiment"):
        exp_id = post_experiment(cur, title, experimenter, exp_date, project_name, keywords, description, exp_ops)
        pa['_new_exp_id'] = exp_id
    if (active_experiment != None and active_experiment != "-1" and exp_ops == "update_experiment"):
        exp_id = post_experiment(cur, title, experimenter, exp_date, project_name, keywords, description, exp_ops, active_experiment)
        pa['_new_exp_id'] = exp_id
    if (exp_ops != None and exp_ops == "insert_exp_grps"):
        grp_rows = qform.getvalue("sgrp_actual_rows")        
        for i in range(0, int(grp_rows)):
            grp_description = qform.getvalue('sgrp_desc' + str(i))
            grp_regex = qform.getvalue('sgrp_regex' + str(i))
            grp_name = qform.getvalue('sgrp_name' + str(i))
            grp_biosample = qform.getvalue('sgrp_biosample' + str(i))
            grp_orgstrain = qform.getvalue('sgrp_orgstrain' + str(i))
            grp_type = qform.getvalue('sgrp_type' + str(i))
            sp_id = qform.getvalue('sgrp_id' + str(i))
            if (sp_id != None and len(sp_id) > 0):
                spid = post_update_groups(cur, grp_name, grp_description, grp_regex, grp_biosample, grp_orgstrain, grp_type, active_experiment,sp_id)
            else:
                spid = post_new_groups(cur, grp_name, grp_description, grp_regex, grp_biosample, grp_orgstrain, grp_type, active_experiment)
            grp_ob = {}
            grp_ob["sample_group_id"] = spid
            grp_ob["name"] = grp_name
            exp_grps.append(grp_ob)   
    if (exp_ops != None and exp_ops == "insert_grp_chr"):
        grp_chrids = qform.getvalue("_grp_chrids")
	ctk = grp_chrids[0:-1].split(",")
        for tk in ctk:
            chromid = tk
            grpid = qform.getvalue('_grp_' + tk)
            rc = post_chrom_groups(cur, chromid, grpid, active_experiment)          
            if (rc == -1):
                pa['_error'] = "Error Posting Sample Group"  
    cur.execute("commit")
    pa['_status'] = "200"
    pa['_exp_grps'] = exp_grps
    print "Content-type: text/html;charset=utf-8\r\n"    
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Update Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()

#if __name__ == "__main__":
#    post_new_credit("new project test")
